

#include "n32g45x.h"
#include "board.h"

#define TIMER7_MAX_COUNT  40000  // 4MHz, 10ms

int hw_delay_init(void)
{
    TIM_TimeBaseInitType TIM_TimeBaseStructure;
    TIM_InitTimBaseStruct(&TIM_TimeBaseStructure);
    TIM_TimeBaseStructure.Period    = TIMER7_MAX_COUNT;
    TIM_TimeBaseStructure.Prescaler = 9 - 1; // 36MHz / 9  = 4MHz
    TIM_TimeBaseStructure.ClkDiv    = 0;
    TIM_TimeBaseStructure.CntMode   = TIM_CNT_MODE_UP;
    TIM_InitTimeBase(TIM7, &TIM_TimeBaseStructure);
    TIM_Enable(TIM7, ENABLE);

    return 0;
}

static uint32_t HwMicroTimerGetCnt(void)
{
    return TIM7->CNT;
}

int hw_delay_us(uint32_t us) // us should be less than 1000
{
    us *= 4;
    us %= TIMER7_MAX_COUNT;
    uint32_t start = HwMicroTimerGetCnt();
    if (us + start > TIMER7_MAX_COUNT) {
        while (HwMicroTimerGetCnt() >= start);
        us -= (TIMER7_MAX_COUNT - start);
        start = 0;
    }
    while ((HwMicroTimerGetCnt() - start) < us);
    return 0;
}

